#include "StdAfx.h"
#include "MeshFacingDir.h"
#include <LitExceptions.h>
#include <LitCore.h>
#include <LitSceneManager.h>

namespace Lit
{
	namespace Editor
	{
		MeshFacingDir::MeshFacingDir( Ogre::Real length, Ogre::SceneManager * mgr, Ogre::SceneNode * parent ){
			if( !mgr ) throw Lit::InvalidParameter( "Ogre::SceneManager*", "Invalid scene manager", EXC_LOC );
			mScene = mgr;
			mObject = mgr->createManualObject();
			mNode = parent ? parent->createChildSceneNode() : Lit::Root::SceneManager()->_sceneManager()->getRootSceneNode()->createChildSceneNode();
			mRootNode = parent ? true : false;
			mLength = length;
			mDir = Lit::Vec3::UNIT_X;

			rebuild();
		}
		MeshFacingDir::~MeshFacingDir( ){
			destroy();
		}

		Ogre::SceneNode* MeshFacingDir::getSceneNode(){ return mNode; }
		Ogre::SceneManager * MeshFacingDir::getSceneManager(){ return mScene; }
		Ogre::ManualObject * MeshFacingDir::getManualObject(){ return mObject; }

		const Ogre::SceneNode* MeshFacingDir::getSceneNode() const{ return mNode; }
		const Ogre::SceneManager * MeshFacingDir::getSceneManager() const{ return mScene; }
		const Ogre::ManualObject * MeshFacingDir::getManualObject() const{ return mObject; }

		const Lit::Vec3& MeshFacingDir::getDirection() const{ return mDir; }
		
		Lit::Real MeshFacingDir::getLength() const{ return mLength; }
		void MeshFacingDir::setLength( Lit::Real length, bool _rebuild ){
			mLength = length;
			if( _rebuild )
				rebuild();
		}
		void MeshFacingDir::setDirection( const Lit::Vec3 &dir, bool _rebuild )
		{
			mDir = dir;
			if( _rebuild )
				rebuild();
		}
		void MeshFacingDir::destroy(){
			if( mScene )
			{
				if( mNode ) mNode->detachAllObjects();
				if( mObject ) mScene->destroyManualObject( mObject );
				if( mNode && mRootNode ) mScene->destroySceneNode( mNode );
				mNode = NULL;
				mObject = NULL;
				mRootNode = false;
			}
		}
		void MeshFacingDir::rebuild()
		{
			if( !mScene || !mObject || !mNode ) return;
			if( !mObject->isAttached() ){
				mObject->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_LINE_LIST );
				
				mObject->position( Lit::Vec3::ZERO );
				mObject->colour( Lit::Color::Red );

				mObject->position( mDir*mLength );
				mObject->colour( Lit::Color::Red );
				
				mObject->end();
				mObject->setDynamic( true );
				mNode->attachObject( mObject );
			}
			else
			{
				mObject->beginUpdate( 0 );
				
				mObject->position( 0.0f, 0.0f, 0.0f );
				mObject->colour( Lit::Color::Red );

				mObject->position( mDir * mLength );
				mObject->colour( Lit::Color::Red );

				mObject->end();
			}
		}

	};
};